<template>
  <el-container>
    <el-header>
      <!-- 查询条件 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
        <el-form-item label="用户名" style="width: 15%">
          <el-input v-model="searchForm.username" placeholder="用户名" @keyup.enter="onSearch"/>
        </el-form-item>
        <el-form-item label="姓名" style="width: 15%">
          <el-input
            v-model="searchForm.fullname"
            placeholder="姓名"
            width="20%"
            @keyup.enter="onSearch"
          />
        </el-form-item>
        <el-form-item label="手机号" style="width: 15%">
          <el-input v-model="searchForm.phone" placeholder="手机号" @keyup.enter="onSearch"/>
        </el-form-item>
        <el-form-item label="员工号" style="width: 15%">
          <el-input v-model="searchForm.employeeNo" placeholder="员工号" @keyup.enter="onSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="default" @click="onReset">重置</el-button>

          <el-button type="default" @click="onAddUser" icon="CirclePlus"
            >新增用户</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-divider direction="horizontal"></el-divider>

    <el-main class="cus-main">
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="id" label="ID" v-if="false" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="fullname" label="姓名" />
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            <el-tag :type="scope.row.type === 1 ? 'primary' : 'info'">
              {{ scope.row.type === 1 ? "登陆用户" : "非登陆用户" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
              {{ scope.row.status === true ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="employeeNo" label="员工号" />

        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="onEdit(scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="onDelete(scope.row)"
              >删除</el-button
            >
            <el-button link type="primary" @click="onAuth(scope.row)"
              >授权</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      >
      </el-pagination>
    </el-main>
  </el-container>
  <!-- 新增用户对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '修改用户' : '新增用户'"
    width="30%"
    header-class="dialog-custom-header"
  >
  <el-divider direction="horizontal" style="width: 95%"></el-divider>
    <el-form :model="newUserForm" label-width="70px">
      <el-form-item label="用户名" required>
        <el-input v-model="newUserForm.username" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="密码" v-if="!isEdit" :required="!isEdit">
        <el-input v-model="newUserForm.password" type="password" />
      </el-form-item>
      <el-form-item label="类型" required>
        <el-select v-model="newUserForm.type" placeholder="请选择用户类型">
          <el-option label="登陆用户" :value="1" />
          <el-option label="非登陆用户" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" v-if="isEdit">
        <el-select v-model="newUserForm.status" placeholder="状态">
          <el-option label="禁用" :value="false" />
          <el-option label="启用" :value="true" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" required>
        <el-input v-model="newUserForm.fullname" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="newUserForm.email" />
      </el-form-item>
      <el-form-item label="电话" required>
        <el-input v-model="newUserForm.phone" />
      </el-form-item>
      <el-form-item label="员工号">
        <el-input v-model="newUserForm.employeeNo" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </template>
  </el-dialog>
  <el-dialog title="角色分配" v-model="roleAssignmentDialogVisible" width="80%">
    <div class="role-assignment-container">
      <!-- 左侧角色列表 -->
      <div
        class="left-panel"
        style="border-right: 1px solid #ccc; padding: 10px"
      >
        <el-input
          v-model="roleSearchQuery.name"
          placeholder="请输入角色名称"
          class="search-input"
          @input="handleRoleSearch"
        >
          <template #prepend>搜索</template>
        </el-input>
        <el-table :data="filteredRoleList" row-key="id" class="role-table">
          <el-table-column prop="id" label="ID" v-if="false" />
          <el-table-column prop="appCode" label="应用编码" v-if="false" />
          <el-table-column prop="name" label="角色" />
          <el-table-column prop="description" label="角色描述" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="bindRole(scope.row)"
                >绑定</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧已分配角色列表 -->
      <div class="right-panel">
        <div class="cus-title">{{ currentUser.username }}已绑定角色</div>
        <el-divider direction="horizontal"></el-divider>
        <el-table :data="assignedRoleList" row-key="id" class="role-table">
          <el-table-column prop="id" label="ID" v-if="false" />

          <el-table-column prop="appCode" label="应用编码" v-if="false" />
          <el-table-column prop="name" label="角色" />
          <el-table-column prop="description" label="角色描述" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="unbindRole(scope.row)"
                >解绑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel" icon="Close">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { get, post, put, del } from "@/utils/request";
const userList = ref([]); // 用户列表数据
const searchForm = reactive({
  username: null,
  fullname: null,
  phone: null,
  employeeNo: null,
});
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的数量
const currentUser = reactive({
  id: null,
  username: null,
  password: null,
  type: null,
  fullname: null,
  email: null,
  phone: null,
  employeeNo: null,
});
const newUserForm = reactive({
  id: null,
  username: null,
  password: null,
  type: null,
  fullname: null,
  email: null,
  phone: null,
  employeeNo: null,
}); // 新增用户数据
const isEdit = ref(false); // 编辑用户数据
const dialogVisible = ref(false);
const listTotal = ref(0);
const roleAssignmentDialogVisible = ref(false); // 控制对话框的显示与隐藏
const roleSearchQuery = reactive({
  name: null,
}); // 搜索框的绑定值
const roleList = ref([]);
const assignedRoleList = ref([]); // 用户已分配的角色列表

const onReset = () => {
  // 重置表单逻辑
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = null;
  });
};

const onEdit = (row) => {
  // 初始化列表
  isEdit.value = true;
  Object.assign(newUserForm, row);
  dialogVisible.value = true;
};
const onSearch = () => {
  // 实现搜索逻辑
  // console.log("搜索条件:", searchForm);
  let params = {
    username: searchForm.username,
    fullname: searchForm.fullname,
    phone: searchForm.phone,
    employeeNo: searchForm.employeeNo,
    page: currentPage.value,
    size: pageSize.value,
  };
  get("/cam/users", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        userList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onDelete = (row) => {
  del("/cam/users/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        userList.value = userList.value.filter((item) => item.id !== row.id);
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};
const onSubmit = async () => {
  let succ = false;
  if (isEdit.value) {
    // 修改租户逻辑
    let payload = {
      employeeNo: newUserForm.employeeNo,
      status: newUserForm.status,
      type: newUserForm.type,
      fullname: newUserForm.fullname,
      email: newUserForm.email,
      phone: newUserForm.phone,
    };
    await put("/cam/users/" + newUserForm.id, payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          const index = userList.value.findIndex(
            (item) => item.id === newUserForm.id
          );
          if (index !== -1) {
            userList.value[index] = {
              ...newUserForm,
            };
          }
          succ = true;
          ElMessage.success("更新成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    // 后端写入
    let payload = {
      employeeNo: newUserForm.employeeNo,
      username: newUserForm.username,
      password: newUserForm.password,
      type: newUserForm.type,
      fullname: newUserForm.fullname,
      email: newUserForm.email,
      phone: newUserForm.phone,
    };
    await post("/cam/users", payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          newUserForm.id = res.data.data.id;
          onSearch();
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
  
};

const onAuth = async (row) => {
  // 授权逻辑
  Object.assign(currentUser, row);
  // 查询选中用的角色列表
  await get("/cam/users/" + currentUser.id)
    .then((res) => {
      if (res.data.code === 0) {
        assignedRoleList.value = res.data.data.roles;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });

  roleAssignmentDialogVisible.value = true;
};
const onAddUser = () => {
  // 新增用户逻辑
  Object.keys(newUserForm).forEach((key) => {
    newUserForm[key] = null;
  });
  isEdit.value = false;
  dialogVisible.value = true;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  onSearch();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  onSearch();
};
// 搜索功能：根据应用或权限过滤角色列表
const filteredRoleList = computed(() => {
  if (!roleSearchQuery.name) {
    return roleList.value;
  }
  return roleList.value.filter((role) =>
    role.name.includes(roleSearchQuery.name)
  );
});

// 绑定角色
const bindRole = async (role) => {
  const isAssigned = assignedRoleList.value.some((item) => item.id === role.id);
  if (!isAssigned) {
    let payload = {
      usersId: [currentUser.id],
    };
    await post("/apm/roles/" + role.id + "/users", payload)
      .then((res) => {
        if (res.data.code === 0) {
          assignedRoleList.value.push(role);
          // onSearch(searchForm.appCode);
          ElMessage.success("绑定成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
};

// 解绑角色
const unbindRole = async (role) => {
  const index = assignedRoleList.value.findIndex((item) => item.id === role.id);
  if (index === -1) {
    return;
  }
  let payload = {
    usersId: [currentUser.id],
  };
  await del("/apm/roles/" + role.id + "/users", payload)
    .then((res) => {
      if (res.data.code === 0) {
        assignedRoleList.value.splice(index, 1);
        // onSearch(searchForm.appCode);
        ElMessage.success("绑定成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

// 取消按钮的点击事件
const handleCancel = () => {
  roleAssignmentDialogVisible.value = false;
};

// 搜索框输入时的处理逻辑
const handleRoleSearch = () => {
  // 可以在这里添加额外的搜索逻辑，例如调用接口获取数据[^1^]
};
onMounted(async () => {
  // 查询所有用户
  let params = {
    code: searchForm.username,
    name: searchForm.fullname,
    phone: searchForm.phone,
    employeeNo: searchForm.employeeNo,
    page: currentPage.value,
    size: pageSize.value,
  };
  await get("/cam/users", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        userList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  await get("/apm/roles")
    .then((res) => {
      if (res.data.code === 0) {
        roleList.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
});
</script>

<style scoped>

.role-assignment-container {
  display: flex;
  justify-content: space-between;
}

.left-panel,
.right-panel {
  width: 48%;
}

.search-input {
  margin-bottom: 10px;
}

.role-table {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}
</style>
